<template>
  <div class="page-content bg-gray-50 min-h-screen">
    <header class="bg-white shadow-sm sticky top-0 z-10">
      <div class="container mx-auto px-4 py-3 flex items-center">
        <router-link to="/tools" class="mr-3 p-1">
          <i class="fas fa-arrow-left text-gray-600"></i>
        </router-link>
        <h1 class="text-lg font-semibold">法律咨询</h1>
      </div>
    </header>

    <main class="container mx-auto px-4 py-4 pb-20">
      <!-- AI助手介绍 -->
      <div class="bg-white rounded-xl shadow-sm mb-4 p-4">
        <div class="flex items-center mb-3">
          <div class="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center mr-3">
            <i class="fas fa-robot text-white text-lg"></i>
          </div>
          <div>
            <h2 class="text-lg font-semibold text-gray-900">AI法律助手</h2>
            <p class="text-sm text-gray-600">智能解答法律问题，提供专业建议</p>
          </div>
        </div>
        
        <div class="bg-blue-50 rounded-lg p-3">
          <div class="flex items-start">
            <i class="fas fa-info-circle text-blue-500 mr-2 mt-0.5"></i>
            <div class="text-sm text-blue-700">
              <p class="font-medium mb-1">服务说明：</p>
              <ul class="space-y-1">
                <li>• 提供24小时智能法律咨询服务</li>
                <li>• 涵盖民事、刑事、商事等各类法律问题</li>
                <li>• 仅供参考，重大事项建议咨询专业律师</li>
              </ul>
            </div>
          </div>
        </div>
        </div>


      <!-- 聊天区域 -->
      <div class="bg-white rounded-xl shadow-sm mb-4">
        <div class="p-4 border-b border-gray-200">
          <h3 class="text-md font-semibold text-gray-900 flex items-center">
            <i class="fas fa-comments text-green-500 mr-2"></i>
            对话记录
          </h3>
        </div>
        
        <div class="chat-container h-96 overflow-y-auto p-4" ref="chatContainer">
          <!-- 欢迎消息 -->
          <div v-if="messages.length === 0" class="text-center py-8">
            <div class="w-16 h-16 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center mx-auto mb-4">
              <i class="fas fa-robot text-white text-2xl"></i>
            </div>
            <h3 class="text-lg font-semibold text-gray-900 mb-2">AI法律助手为您服务</h3>
            <p class="text-gray-600 text-sm">请输入您的法律问题，我将为您提供专业解答</p>
          </div>

          <!-- 聊天消息 -->
          <div v-for="(message, index) in messages" :key="index" class="mb-4">
            <!-- 用户消息 -->
            <div v-if="message.type === 'user'" class="flex justify-end">
              <div class="max-w-xs lg:max-w-md px-4 py-2 bg-blue-500 text-white rounded-lg rounded-br-none">
                {{ message.content }}
              </div>
            </div>
            
            <!-- AI回复 -->
            <div v-else class="flex justify-start">
              <div class="flex items-start max-w-xs lg:max-w-md">
                <div class="w-8 h-8 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center mr-2 flex-shrink-0">
                  <i class="fas fa-robot text-white text-sm"></i>
                </div>
                <div class="px-4 py-2 bg-gray-100 text-gray-800 rounded-lg rounded-bl-none">
                  <div v-if="message.loading" class="flex items-center space-x-2">
                    <div class="flex space-x-1">
                      <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                      <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.1s"></div>
                      <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.2s"></div>
                    </div>
                    <span class="text-sm text-gray-500">正在思考...</span>
                  </div>
                  <div v-else v-html="formatMessage(message.content)"></div>
                </div>
              </div>
            </div>
            </div>
          </div>
        </div>

      <!-- 输入区域 -->
      <div class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4">
        <div class="container mx-auto max-w-4xl">
          <div class="flex items-end space-x-3">
            <div class="flex-1">
              <textarea
                v-model="userInput"
                @keydown.enter.prevent="sendMessage"
                placeholder="请输入您的法律问题..."
                class="w-full px-4 py-3 border border-gray-300 rounded-lg resize-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                rows="2"
                :disabled="isLoading"
              ></textarea>
            </div>
            <button
              @click="sendMessage"
              :disabled="!userInput.trim() || isLoading"
              class="px-6 py-3 bg-blue-500 text-white rounded-lg font-medium hover:bg-blue-600 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors flex items-center"
            >
              <i v-if="isLoading" class="fas fa-spinner fa-spin mr-2"></i>
              <i v-else class="fas fa-paper-plane mr-2"></i>
              {{ isLoading ? '发送中' : '发送' }}
            </button>
          </div>
          
          <!-- 功能按钮 -->
          <div class="flex items-center justify-between mt-3 text-sm text-gray-500">
            <div class="flex items-center space-x-4">
              <button @click="clearChat" class="flex items-center hover:text-gray-700">
                <i class="fas fa-trash mr-1"></i>
                清空对话
              </button>
              <button @click="exportChat" class="flex items-center hover:text-gray-700">
                <i class="fas fa-download mr-1"></i>
                导出记录
              </button>
            </div>
            <div class="text-xs">
              按 Enter 发送，Shift + Enter 换行
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
export default {
  name: 'LegalConsultation',
  data() {
    return {
      userInput: '',
      isLoading: false,
      messages: [],
    }
  },
  methods: {
    
    async sendMessage() {
      if (!this.userInput.trim() || this.isLoading) return
      
      const userMessage = this.userInput.trim()
      this.userInput = ''
      
      // 添加用户消息
      this.messages.push({
        type: 'user',
        content: userMessage,
        timestamp: new Date()
      })
      
      // 添加AI加载消息
      this.messages.push({
        type: 'ai',
        content: '',
        loading: true,
        timestamp: new Date()
      })
      
      this.isLoading = true
      this.scrollToBottom()
      
      try {
        // 模拟AI回复
        await this.simulateAIResponse(userMessage)
      } catch (error) {
        console.error('AI回复失败:', error)
        this.messages[this.messages.length - 1] = {
          type: 'ai',
          content: '抱歉，服务暂时不可用，请稍后重试。',
          loading: false,
          timestamp: new Date()
        }
      } finally {
        this.isLoading = false
        this.scrollToBottom()
      }
    },
    
    async simulateAIResponse(userMessage) {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 1500 + Math.random() * 1000))
      
      // 根据问题类型生成回复
      const response = this.generateAIResponse(userMessage)
      
      // 更新最后一条消息
      this.messages[this.messages.length - 1] = {
        type: 'ai',
        content: response,
        loading: false,
        timestamp: new Date()
      }
    },
    
    generateAIResponse(question) {
      const responses = {
        '合同违约': `
          <p><strong>合同违约的处理方式：</strong></p>
          <ol class="list-decimal list-inside mt-2 space-y-2">
            <li><strong>协商解决：</strong>首先与对方协商，寻求友好解决方案</li>
            <li><strong>要求履行：</strong>可以要求违约方继续履行合同义务</li>
            <li><strong>损害赔偿：</strong>要求违约方赔偿因违约造成的损失</li>
            <li><strong>解除合同：</strong>严重违约时可以解除合同并要求赔偿</li>
            <li><strong>法律途径：</strong>协商不成可以申请仲裁或提起诉讼</li>
          </ol>
          <p class="mt-3 text-sm text-blue-600"><strong>建议：</strong>保存好相关证据材料，如合同原件、履行证明、损失证据等。</p>
        `,
        '交通事故': `
          <p><strong>交通事故责任认定：</strong></p>
          <ol class="list-decimal list-inside mt-2 space-y-2">
            <li><strong>报警处理：</strong>及时报警，由交警部门出具事故认定书</li>
            <li><strong>责任划分：</strong>根据当事人违法行为与事故的因果关系确定责任</li>
            <li><strong>责任类型：</strong>全部责任、主要责任、同等责任、次要责任、无责任</li>
            <li><strong>保险理赔：</strong>联系保险公司进行理赔</li>
            <li><strong>协商赔偿：</strong>就医疗费、误工费等损失进行协商</li>
          </ol>
          <p class="mt-3 text-sm text-blue-600"><strong>提醒：</strong>对事故认定书有异议的，可在3日内申请复核。</p>
        `,
        '房屋买卖': `
          <p><strong>房屋买卖纠纷解决：</strong></p>
          <ol class="list-decimal list-inside mt-2 space-y-2">
            <li><strong>查看合同：</strong>仔细查看购房合同约定的权利义务</li>
            <li><strong>收集证据：</strong>保存购房合同、付款凭证、交房记录等</li>
            <li><strong>协商解决：</strong>与开发商或卖方协商解决争议</li>
            <li><strong>投诉举报：</strong>向住建部门或消费者协会投诉</li>
            <li><strong>法律维权：</strong>必要时通过仲裁或诉讼维护权益</li>
          </ol>
          <p class="mt-3 text-sm text-blue-600"><strong>常见问题：</strong>延期交房、质量问题、面积差异、产权纠纷等。</p>
        `,
        '劳动合同': `
          <p><strong>劳动合同纠纷处理：</strong></p>
          <ol class="list-decimal list-inside mt-2 space-y-2">
            <li><strong>内部协商：</strong>先与用人单位协商解决</li>
            <li><strong>劳动调解：</strong>申请企业劳动争议调解委员会调解</li>
            <li><strong>劳动仲裁：</strong>向劳动仲裁委员会申请仲裁</li>
            <li><strong>法院诉讼：</strong>对仲裁裁决不服可以起诉</li>
            <li><strong>证据收集：</strong>保存劳动合同、工资条、考勤记录等</li>
          </ol>
          <p class="mt-3 text-sm text-blue-600"><strong>时效提醒：</strong>劳动仲裁申请时效为1年，从知道或应当知道权利被侵害之日起计算。</p>
        `,
        '离婚财产': `
          <p><strong>离婚财产分割原则：</strong></p>
          <ol class="list-decimal list-inside mt-2 space-y-2">
            <li><strong>夫妻共同财产：</strong>婚后取得的财产原则上平等分割</li>
            <li><strong>个人财产：</strong>婚前财产、继承或赠与的专属财产归个人</li>
            <li><strong>照顾原则：</strong>照顾子女、女方和无过错方的利益</li>
            <li><strong>协议优先：</strong>双方可以协议约定财产分割方式</li>
            <li><strong>债务承担：</strong>共同债务由双方共同承担</li>
          </ol>
          <p class="mt-3 text-sm text-blue-600"><strong>建议：</strong>详细清理夫妻共同财产，包括房产、存款、投资、债务等。</p>
        `,
        '借款追讨': `
          <p><strong>借款追讨的方法：</strong></p>
          <ol class="list-decimal list-inside mt-2 space-y-2">
            <li><strong>友好协商：</strong>与债务人协商还款计划</li>
            <li><strong>发送催收函：</strong>书面催收并保留证据</li>
            <li><strong>申请支付令：</strong>符合条件的可申请支付令</li>
            <li><strong>提起诉讼：</strong>向法院起诉要求还款</li>
            <li><strong>申请执行：</strong>胜诉后申请强制执行</li>
          </ol>
          <p class="mt-3 text-sm text-blue-600"><strong>重要：</strong>注意诉讼时效为3年，及时主张权利。准备好借条、转账记录等证据。</p>
        `
      }
      
      // 根据关键词匹配回复
      for (const [keyword, response] of Object.entries(responses)) {
        if (question.includes(keyword)) {
          return response
        }
      }
      
      // 默认回复
      return `
        <p>感谢您的咨询。根据您的问题，我建议：</p>
        <ol class="list-decimal list-inside mt-2 space-y-2">
          <li><strong>详细描述：</strong>请提供更多具体情况，以便给出准确建议</li>
          <li><strong>收集证据：</strong>保存相关的合同、凭证、记录等材料</li>
          <li><strong>寻求帮助：</strong>可以咨询专业律师获取详细建议</li>
          <li><strong>法律途径：</strong>必要时通过法律途径维护自身权益</li>
        </ol>
        <p class="mt-3 text-sm text-blue-600"><strong>温馨提示：</strong>具体情况需要结合实际案例分析，建议咨询专业律师获取更准确的法律意见。</p>
      `
    },
    
    formatMessage(content) {
      return content
    },
    
    clearChat() {
      if (confirm('确定要清空所有对话记录吗？')) {
        this.messages = []
      }
    },
    
    exportChat() {
      if (this.messages.length === 0) {
        alert('暂无对话记录可导出')
        return
      }
      
      let content = '法律咨询对话记录\n'
      content += '='.repeat(50) + '\n\n'
      
      this.messages.forEach((message, index) => {
        const time = message.timestamp.toLocaleString()
        const sender = message.type === 'user' ? '用户' : 'AI助手'
        content += `${sender} (${time}):\n`
        content += message.content.replace(/<[^>]*>/g, '') + '\n\n'
      })
      
      const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `法律咨询记录_${new Date().toISOString().slice(0, 10)}.txt`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    },
    
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.chatContainer
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    }
  }
}
</script>

<style scoped>
.chat-container {
  scroll-behavior: smooth;
}

.chat-container::-webkit-scrollbar {
  width: 6px;
}

.chat-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

.animate-bounce {
  animation: bounce 1.4s infinite ease-in-out both;
}
</style>

